'use client'

import { Loader2 } from "lucide-react"
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import React, { useRef, useState } from 'react'

export default function ApiServerTest() {
    const [server, setServer] = useState("wss://ws.pick-fun.com:18089");
    const [message, setMessage] = useState("");
    const [busy, setBusy] = useState(false);
    const totalRef = useRef(0);
    const successRef = useRef(0);
    function connectAsync() {
        return new Promise((resolve, reject) => {
            const socket = new WebSocket(server);
            socket.onopen = function () {
                resolve(true);
            };

            socket.onmessage = function (event) {
                console.log('Received message from server:', event.data)
            };

            socket.onerror = function (error) {
                resolve(false);
            };

            socket.onclose = function () {
                console.log('Connection closed');
            };
        })

    }

    async function test() {
        totalRef.current = 0;
        successRef.current = 0;
        setBusy(true);
        setMessage("Testing...");
        try {
            for (let i = 0; i < 3; i++) {
                const result = await connectAsync();
                if (result) {
                    successRef.current += 1;
                }
                totalRef.current += 1;
            }
            var msg = `Total Test: ${totalRef.current}, Success: ${successRef.current} (${Math.round(successRef.current / totalRef.current * 100)}%)`;
            setMessage(msg);
        } catch (error) {
            setMessage("Error");
        } finally {
            setBusy(false);
        }
    }

    return (
        <div className='flex flex-col flex-wrap content-center p-4'>
            <p className="mb-4 text-sm text-gray-500">Note: Test will take a few seconds, please wait</p>
            <div className='flex flex-row w-fit gap-x-2 mb-2 '>
                <Input className='w-64' value={server} onChange={(e) => setServer(e.target.value)} />
                <Button onClick={test} disabled={busy}>
                    {busy && <Loader2 className="animate-spin w-4 h-4 mr-2" />}
                    Test
                </Button>
            </div>
            <p className="text-sm">{message}</p>
        </div>
    )
}
